package com.ruoyi.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.business.domain.FilePerson;
import com.ruoyi.business.domain.FileTransferOut;
import com.ruoyi.business.domain.bo.FileTransferOutBo;
import com.ruoyi.business.domain.vo.FileTransferOutVo;
import com.ruoyi.business.mapper.FileTransferOutMapper;
import com.ruoyi.business.service.IFileExternalUnitsFormPersonService;
import com.ruoyi.business.service.IFileTransferOutService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringExtUtils;
import com.ruoyi.workflow.domain.vo.TaskWaitingVo;
import com.ruoyi.workflow.service.IProcessInstanceService;
import com.ruoyi.workflow.service.impl.TaskServiceImpl;
import com.ruoyi.workflow.utils.WorkFlowUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 档案转出Service业务层处理
 *
 * @author sal
 * @date 2024-11-25
 */
@RequiredArgsConstructor
@Service
public class FileTransferOutServiceImpl implements IFileTransferOutService {

    private final FileTransferOutMapper baseMapper;
    private final IProcessInstanceService iProcessInstanceService;
    private final IFileExternalUnitsFormPersonService fileExternalUnitsFormPersonService;
    private final TaskServiceImpl taskService;
    /**
     * 查询档案转出
     */
    @Override
    public FileTransferOutVo queryById(Long id){
        FileTransferOutVo fileTransferOutVo = baseMapper.selectVoById(id);
        WorkFlowUtils.setStatusFileValue(fileTransferOutVo, String.valueOf(fileTransferOutVo.getId()));
        return fileTransferOutVo;
    }

    /**
     * 查询档案转出列表
     */
    @Override
    public TableDataInfo<FileTransferOutVo> queryPageList(FileTransferOutBo bo, PageQuery pageQuery) {
        MPJLambdaWrapper<FileTransferOut> lqw = buildQueryWrapper(bo);
        Page<FileTransferOutVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<FileTransferOutVo> records = result.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            List<String> collectIds = records.stream().map(FileTransferOutVo::getId).collect(Collectors.toList());
            WorkFlowUtils.setStatusListFileValue(records, collectIds, "id");
        }
        result.setRecords(records);
        return TableDataInfo.build(result);
    }
    @Override
    public TableDataInfo<FileTransferOutVo> queryPageList1(FileTransferOutBo bo, PageQuery pageQuery) {
        MPJLambdaWrapper<FileTransferOut> lqw = buildQueryWrapper(bo);
        Page<FileTransferOutVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<FileTransferOutVo> records = result.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            List<String> collectIds = records.stream().map(FileTransferOutVo::getId).collect(Collectors.toList());
            WorkFlowUtils.setStatusListFileValue(records, collectIds, "id");
        }
        List<TaskWaitingVo> taskList = taskService.getTaskWaitByKey(pageQuery, "transferOut");
        for (TaskWaitingVo taskWaitingVo : taskList) {
            for (FileTransferOutVo record : records) {
                if (record.getId().equals(taskWaitingVo.getBusinessKey())) {
                    record.setProcessInstanceId(taskWaitingVo.getProcessInstanceId());
                    record.setTaskId(taskWaitingVo.getId());
                    record.setTaskDefinitionKey(taskWaitingVo.getTaskDefinitionKey());
                    break;
                }
            }
        }
        result.setRecords(records);
        return TableDataInfo.build(result);
    }

    /**
     * 查询档案转出列表
     */
    @Override
    public List<FileTransferOutVo> queryList(FileTransferOutBo bo) {
        MPJLambdaWrapper<FileTransferOut> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private MPJLambdaWrapper<FileTransferOut> buildQueryWrapper(FileTransferOutBo bo) {
        MPJLambdaWrapper<FileTransferOut> lqw = new MPJLambdaWrapper<FileTransferOut>();
        lqw.selectAll(FileTransferOut.class)
            .selectAs(FilePerson::getName,FileTransferOut::getGoToPersonName)
            .selectAs(SysUser::getNickName,FileTransferOut::getAttnName)
            .leftJoin(SysUser.class, SysUser::getUserId, FileTransferOut::getAttn)
            .leftJoin(FilePerson.class, FilePerson::getId, FileTransferOut::getGoToPerson)
            .eq(bo.getGoToPerson() != null, FileTransferOut::getGoToPerson, bo.getGoToPerson())
            .eq(bo.getType() != null, FileTransferOut::getType, bo.getType())
            .eq(bo.getAttn() != null, FileTransferOut::getAttn, bo.getAttn());
        return lqw;
    }

    /**
     * 新增档案转出
     */
    @Override
    public FileTransferOut insertByBo(FileTransferOutBo bo) {
        FileTransferOut add = BeanUtil.toBean(bo, FileTransferOut.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId().toString());
        }
        return add;
    }

    /**
     * 修改档案转出
     */
    @Override
    public FileTransferOut updateByBo(FileTransferOutBo bo) {
        FileTransferOut update = BeanUtil.toBean(bo, FileTransferOut.class);
        validEntityBeforeSave(update);
        baseMapper.updateById(update);
        return update;

    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FileTransferOut entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除档案转出
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (Long id : ids) {
            String processInstanceId = iProcessInstanceService.getProcessInstanceId(id.toString());
            if (StringExtUtils.isNotEmpty(processInstanceId)) { //删除相关流程数据
                iProcessInstanceService.deleteRuntimeProcessAndHisInst(processInstanceId);

            }
            fileExternalUnitsFormPersonService.deleteByFromId(id);
        }


        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
